package cn.icare.cms.impl;

import cn.icare.cms.DateUtil;
import cn.icare.cms.MemberCouponService;
import cn.icare.cms.StringUtil;
import cn.icare.cms.dao.mapper.CustomMapper;
import cn.icare.cms.dao.mapper.MemberCouponMapper;
import cn.icare.cms.dao.po.Area;
import cn.icare.cms.dao.po.MemberCoupon;
import cn.icare.cms.model.enums.CommonStatusEnum;
import cn.icare.cms.model.enums.CouponUseStatusEnum;
import cn.icare.cms.model.ro.AddMemberCouponRO;
import cn.icare.cms.model.vo.rest.MsgDatasVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MemberCouponServiceImpl implements MemberCouponService {

    @Resource
    private MemberCouponMapper memberCouponMapper;

    @Resource
    private CustomMapper customMapper;

    private final Logger logger = LoggerFactory.getLogger(MemberCouponServiceImpl.class);


    @Override
    public Integer createOne(MemberCoupon ro) {
        try {
            MemberCoupon model = ro;
            model.setStatus(CouponUseStatusEnum.NO_USE.getCode());
            model.setCreatetime(new Date());
            int result = this.memberCouponMapper.insertSelective(model);
            if (result > 0) {
                return model.getId();
            }
        } catch (Exception ex) {
            this.logger.error("createOne异常", ex);
        }
        return 0;
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {
        try {
            MemberCoupon model = new MemberCoupon();
            model.setId(id);
            model.setStatus(status);
            model.setCreatetime(new Date());
            int result = this.memberCouponMapper.updateByPrimaryKeySelective(model);
            if (result > 0) {
                return true;
            }
        } catch (Exception ex) {
            this.logger.error("createOne异常", ex);
        }
        return false;
    }


    @Override
    public MsgDatasVO getList(Long memberId, Integer status) {

        MsgDatasVO result = new MsgDatasVO();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            stringBuilder.append("SELECT mc.couponid,c.`name`,c.num,c.neednum,c.type,mc.starttime,mc.endtime ");
            stringBuilder.append(" FROM t_member_coupon mc INNER JOIN t_coupon c on mc.couponid = c.id ");
            stringBuilder.append(" where mc.memberid=" + memberId);

            if (status != null && status > -1) {
                switch (status) {
                    case 0: {
                        //已使用
                        stringBuilder.append(" and  mc.status=0");
                        break;
                    }
                    case 1: {
                        //未使用
                        stringBuilder.append(" and  mc.status=1");
                        break;
                    }
                    case 2: {
                        //未使用的过期券
                        stringBuilder.append(" and  mc.status=1 and mc.endtime<now()");
                        break;
                    }
                    default:
                        break;
                }
            }
            stringBuilder.append(" ORDER BY mc.endtime asc");
            List<Map<String, Object>> dataList = this.customMapper.select(stringBuilder.toString());
            if (dataList != null && dataList.size() > 0) {
                dataList.parallelStream().forEach(map -> {
                    map.put("starttime", DateUtil.formateToDate((Date) map.get("starttime")));
                    map.put("endtime", DateUtil.formateToDate((Date) map.get("endtime")));
                });
            }
            result.setTotal(dataList.size());
            result.setDatas(dataList);

        } catch (Exception e) {
            this.logger.error("getList 异常", e);
        }
        return result;
    }

    @Override
    public Map<String, Object> getMemberCouponOne(Long memberId, Integer couponId) {
        String sql = "SELECT b.num,b.neednum,b.`name` from t_member_coupon a,t_coupon b where a.couponid=b.id" +
                " and a.`status`=" + CommonStatusEnum.EABLED.getCode() + " and b.createtime<=NOW()" +
                " and b.endtime>=NOW() and a.memberid=" + memberId + " and a.couponid=" + couponId;
        List<Map<String, Object>> list = customMapper.select(sql);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public MsgDatasVO getListByOrderAmount(Long memberId, Integer type, BigDecimal amount) {
        MsgDatasVO result = new MsgDatasVO();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            stringBuilder.append("SELECT mc.couponid,c.`name`,c.num,c.neednum,c.type,mc.starttime,mc.endtime ");
            stringBuilder.append(" FROM t_member_coupon mc INNER JOIN t_coupon c on mc.couponid = c.id ");
            stringBuilder.append(" where mc.memberid=" + memberId + " and mc.status=1");
            stringBuilder.append(" and mc.starttime<=now() and mc.endtime>=now()");

            if (type == 1) {

                //可用接口
                stringBuilder.append(" and c.neednum<=" + amount);
            } else if (type == 0) {
                //不可用接口
                stringBuilder.append(" and c.neednum>" + amount);
            }
            //排序换成根据优惠券金额从高到低显示
            //stringBuilder.append(" ORDER BY mc.endtime asc");
            stringBuilder.append(" ORDER BY c.num DESC");
            List<Map<String, Object>> dataList = this.customMapper.select(stringBuilder.toString());
            if (dataList != null && dataList.size() > 0) {
                dataList.parallelStream().forEach(map -> {
                    map.put("starttime", DateUtil.formateToDate((Date) map.get("starttime")));
                    map.put("endtime", DateUtil.formateToDate((Date) map.get("endtime")));
                });
            }
            result.setTotal(dataList.size());
            result.setDatas(dataList);

        } catch (Exception e) {
            this.logger.error("getList 异常", e);
        }
        return result;
    }

    @Override
    public boolean exists(Long memberId, Integer couponId) {
        Example example = new Example(MemberCoupon.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("memberid", memberId);
        criteria.andEqualTo("couponid", couponId);
        MemberCoupon coupon = this.memberCouponMapper.selectOneByExample(example);
        if (coupon != null)
            return true;
        else
            return false;
    }


}
